package com.example.routes

import com.example.data.model.ASMR
import com.example.data.model.Collect
import com.example.data.model.History
import com.example.data.model.Response
import com.example.service.ASMRService
import com.example.service.CollectService
import com.example.service.HistoryService
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.auth.jwt.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*

fun Route.asmrRouting(asmrService: ASMRService, historyService: HistoryService, collectService: CollectService) {
    route("asmr") {
        get {
            val page = call.parameters["page"]?.toInt() ?: 1
            val pageSize = call.parameters["pageSize"]?.toInt() ?: 10
            val sort = call.parameters["sort"]
            val order = call.parameters["order"]
            val all = asmrService.getAll(page, pageSize, order, sort)
//            val list = mutableListOf<ASMR>()
//            while (list.size < 20) {
//                list.addAll(all)
//            }
            call.respond(HttpStatusCode.OK, Response("获取成功", true, all))
        }
        get("tag") {
            val tag = call.parameters["tag"]?.toInt() ?: return@get call.respondText(
                "没有传入分类", status = HttpStatusCode.BadRequest
            )
            val page = call.parameters["page"]?.toInt() ?: 1
            val pageSize = call.parameters["pageSize"]?.toInt() ?: 20
            val all = asmrService.getAllByTag(page, pageSize, tag)
            call.respond(HttpStatusCode.OK, Response("获取成功", true, all))
        }
        get("search") {
            val name = call.parameters["name"]
            val page = call.parameters["page"]?.toInt() ?: 1
            val pageSize = call.parameters["pageSize"]?.toInt() ?: 20
            val all = asmrService.getAll(page, pageSize, name)
            call.respond(HttpStatusCode.OK, Response("获取成功", true, all))
        }
        get("{id}") {
            val id = call.parameters["id"]?.toInt() ?: return@get call.respondText(
                "没有传入Id", status = HttpStatusCode.BadRequest
            )
            val detail = asmrService.getDetail(id)
            call.respond(detail)
        }
        get("tags") {
            call.respond(asmrService.getTags())
        }
    }
    //只有token才可以访问
    authenticate {
        get("isExpires") {
            call.respond(HttpStatusCode.OK, Response("token还未过期", true, null))
        }
        get("asmr/recommend") {
            val principal = call.principal<JWTPrincipal>()
            val username = principal!!.payload.getClaim("username").asString()
            val asmrIdSet = HashSet<Int>()
            historyService.getHistory(username, 1, 5).map { it.asmrId }.forEach { asmrIdSet.add(it) }
            collectService.get(username, 1, 5).map { it.asmrId }.forEach(asmrIdSet::add)
            println("asmrIds:$asmrIdSet")
            if (asmrIdSet.isEmpty()) {
                call.respond(HttpStatusCode.OK, Response("获取成功", true, emptyList<ASMR>()))
                return@get
            }
            val tagIdSet = HashSet<String>()
            asmrService.getTagStringByIds(asmrIdSet).forEach {
                it.split(",").forEach { a ->
                    tagIdSet.add(a)
                }
            }
            println("tagIds:$tagIdSet")
            val stringBuilder = StringBuilder()
            tagIdSet.forEachIndexed { index, s ->
                stringBuilder.append(s)
                if (index != tagIdSet.size - 1) {
                    stringBuilder.append("|")
                }
            }
            call.respond(
                HttpStatusCode.OK,
                Response("获取成功", true, asmrService.getASMRByTagString(stringBuilder.toString()))
            )
        }
        route("history") {
            get {
                val principal = call.principal<JWTPrincipal>()
                val username = principal!!.payload.getClaim("username").asString()
                val page = call.parameters["page"]?.toInt() ?: 1
                val pageSize = call.parameters["pageSize"]?.toInt() ?: 20
                val history = historyService.getHistory(username, page, pageSize)
                call.respond(HttpStatusCode.OK, history)
            }
            post("add") {
                val receive = call.receive<History>()
                if (receive.username.isNullOrEmpty()) {
                    val principal = call.principal<JWTPrincipal>()
                    receive.username = principal!!.payload.getClaim("username").asString()
                }
                val b = historyService.add(receive)
                if (b) {
                    call.respond(Response("添加成功", true, null))
                } else {
                    call.respond(Response("添加失败", false, null))
                }
            }
            get("delete/{id}") {
                val id = call.parameters["id"]?.toInt() ?: return@get call.respondText(
                    "没有传入Id", status = HttpStatusCode.BadRequest
                )
                val b = historyService.delete(id)
                if (b) {
                    call.respond(Response("删除成功", true, null))
                } else {
                    call.respond(Response("删除失败", false, null))
                }
            }
            get("clear") {
                val principal = call.principal<JWTPrincipal>()
                val username = principal!!.payload.getClaim("username").asString()
                val b = historyService.clear(username)
                if (b) {
                    call.respond(Response("删除成功", true, null))
                } else {
                    call.respond(Response("删除失败", false, null))
                }
            }
        }
        route("collect") {
            get {
                val principal = call.principal<JWTPrincipal>()
                val username = principal!!.payload.getClaim("username").asString()
                val page = call.parameters["page"]?.toInt() ?: 1
                val pageSize = call.parameters["pageSize"]?.toInt() ?: 20
                val collectList = collectService.get(username, page, pageSize)
                call.respond(HttpStatusCode.OK, collectList)
            }
            post("add") {
                val receive = call.receive<Collect>()
                if (receive.username == null || receive.username!!.isEmpty()) {
                    val principal = call.principal<JWTPrincipal>()
                    receive.username = principal!!.payload.getClaim("username").asString()
                }
                val b = collectService.add(receive)
                if (b) {
                    call.respond(Response("添加成功", true, null))
                } else {
                    call.respond(Response("添加失败", false, null))
                }
            }
            get("delete/{asmrId}") {
                val id = call.parameters["asmrId"]?.toInt() ?: return@get call.respondText(
                    "没有传入asmrId", status = HttpStatusCode.BadRequest
                )
                val principal = call.principal<JWTPrincipal>()
                val username = principal!!.payload.getClaim("username").asString()
                val b = collectService.delete(id, username)
                if (b) {
                    call.respond(Response("删除成功", true, null))
                } else {
                    call.respond(Response("删除失败", false, null))
                }
            }
            get("clear") {
                val principal = call.principal<JWTPrincipal>()
                val username = principal!!.payload.getClaim("username").asString()
                val b = collectService.clear(username)
                if (b) {
                    call.respond(Response("删除成功", true, null))
                } else {
                    call.respond(Response("删除失败", false, null))
                }
            }
            get("isCollect/{asmrId}") {
                val asmrId = call.parameters["asmrId"]?.toInt() ?: return@get call.respondText(
                    "没有传入asmrId", status = HttpStatusCode.BadRequest
                )
                val principal = call.principal<JWTPrincipal>()
                val username = principal!!.payload.getClaim("username").asString()
                val b = collectService.isCollect(asmrId, username)
                if (b) {
                    call.respond(Response("存在该收藏", true, null))
                } else {
                    call.respond(Response("不存在该收藏", false, null))
                }
            }
        }
    }
}